import SparkMD5 from 'spark-md5';

onmessage = async (e) => {
    const {
        file,
        start,
        end,
        CHUNK_SIZE
    } = e.data;
    const result = [];
    for (let i = start; i < end; i++) {
        const promise = createChunk(file, i, CHUNK_SIZE);
        result.push(promise);
    }
    const chunks = await Promise.all(result);
    postMessage(chunks);
};

async function createChunk(file, index, chunkSize) {
    return new Promise((resolve, reject) => {
        const start = index * chunkSize;
        const end = Math.min(start + chunkSize, file.size);

        const reader = file.slice(start, end).stream().getReader();
        const spark = new SparkMD5.ArrayBuffer();
        const chunks = [];
        let size = 0;

        reader.read().then(function processText({ done, value }) {
            if (done) {
                // Convert chunks to ArrayBuffer and calculate hash
                const arrayBuffer = new Uint8Array(size).buffer;
                let offset = 0;
                for (const chunk of chunks) {
                    new Uint8Array(arrayBuffer, offset, chunk.length).set(chunk);
                    offset += chunk.length;
                }

                spark.append(arrayBuffer);
                const hash = spark.end();
                // Recreate the Blob from the accumulated chunks
                const blob = new Blob(chunks);
                resolve({ start, end, index, hash, blob });
                return;
            }
            chunks.push(value);
            size += value.length;
            return reader.read().then(processText);
        }).catch(reject);
    });
}